import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// MQTT接口定义
interface AppInfoResponse {
  code: number
  msg: string
  appName: string
  appVersion: string
}

interface WarnStatusResponse {
  code: number
  msg: string
  data: Array<{
    time: string
    identification: string
    content: string
  }>
}

// MQTT相关API
const mqttAPI = {
  // 初始化MQTT连接
  initialize: (brokerUrl: string, username: string, password: string, clientId: string) =>
    ipcRenderer.invoke('mqtt-initialize', brokerUrl, username, password, clientId),

  // 获取MQTT状态
  getStatus: () => ipcRenderer.invoke('mqtt-get-status'),

  // 获取应用信息
  getAppInfo: () => ipcRenderer.invoke('mqtt-get-app-info'),

  // 获取警告状态
  getWarnStatus: () => ipcRenderer.invoke('mqtt-get-warn-status'),

  // 请求应用信息
  requestAppInfo: () => ipcRenderer.invoke('mqtt-request-app-info'),

  // 请求警告状态数据
  requestWarnStatus: () => ipcRenderer.invoke('mqtt-request-warn-status'),

  // 重新连接
  reconnect: () => ipcRenderer.invoke('mqtt-reconnect'),

  // 断开连接
  disconnect: () => ipcRenderer.invoke('mqtt-disconnect'),

  // 监听应用信息更新
  onAppInfoUpdate: (callback: (appInfo: AppInfoResponse) => void) => {
    ipcRenderer.on('mqtt-app-info-update', (_event, appInfo: AppInfoResponse) => {
      callback(appInfo)
    })
  },

  // 监听警告状态更新
  onWarnStatusUpdate: (callback: (warnStatus: WarnStatusResponse) => void) => {
    ipcRenderer.on('mqtt-warn-status-update', (_event, warnStatus: WarnStatusResponse) => {
      callback(warnStatus)
    })
  },

  // 移除应用信息更新监听
  removeAppInfoUpdateListener: () => {
    ipcRenderer.removeAllListeners('mqtt-app-info-update')
  },

  // 移除警告状态更新监听
  removeWarnStatusUpdateListener: () => {
    ipcRenderer.removeAllListeners('mqtt-warn-status-update')
  }
}

// Custom APIs for renderer
const api = {
  mqtt: mqttAPI
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
